package com.cskaoyan.service;

import com.cskaoyan.bean.bo.GoodsInfoBo;
import com.cskaoyan.bean.entity.*;
import com.cskaoyan.bean.vo.*;
import com.cskaoyan.mapper.*;
import com.cskaoyan.utils.LimitListSizeUtil;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Auther Wenjian_Yang
 * @Date 2021/10/18
 */
@Service
public class GoodsServiceImpl implements GoodsService {

    @Autowired
    GoodsMapper goodsMapper;
    @Autowired
    BrandMapper brandMapper;
    @Autowired
    CategoryMapper categoryMapper;
    @Autowired
    GoodsAttributeMapper goodsAttributeMapper;
    @Autowired
    GoodsProductMapper goodsProductMapper;
    @Autowired
    GoodsSpecificationMapper goodsSpecificationMapper;

    @Autowired
    CommentMapper commentMapper;

    @Autowired
    IssueMapper issueMapper;

    @Autowired
    UserMapper userMapper;

//    @Override
//    public BasePageData query(String goodsId, String goodsSn, String name , BaseParam param) {
//        if(param.getLimit() > 0) {
//            //配置分页信息 → 在执行预编译过程，会帮你拼接分页的sql语句
//            PageHelper.startPage(param.getPage(), param.getLimit());
//        }
//        if(param.getSort() == null){
//            param.setSort("id");
//        }
//        if(param.getOrder() == null){
//            param.setOrder("");
//        }
//            GoodsExample goodsExample = new GoodsExample();
//            //构造条件 → List<Criterion> → and方法做的事情就是构造一个Criterion的对象添加到List里
//            // 如果 name 不为null，拼接条件 and name like '%songge%'
//            GoodsExample.Criteria criteria = goodsExample.createCriteria();
//
//            if (name != null && !"".equals(name)) {
//                criteria.andNameLike("%" + name + "%");
//            }
//            if (goodsId != null && !"".equals(goodsId)) {
//                criteria.andIdLike("%" + goodsId + "%");
//            }
//            if (goodsSn != null && !"".equals(goodsSn)) {
//                criteria.andGoodsSnLike("%" + goodsSn + "%");
//            }
//            // 未删除的
//            criteria.andDeletedEqualTo(false);
//            goodsExample.setOrderByClause(param.getSort() + " " + param.getOrder());
//            List<Goods> goods = goodsMapper.selectByExample(goodsExample);
//            return BasePageData.ok(goods);
//    }
@Override
public BasePageData query(String goodsId, String goodsSn, String name , BaseParam param) {
    if(param.getLimit() > 0) {
        //配置分页信息 → 在执行预编译过程，会帮你拼接分页的sql语句
        PageHelper.startPage(param.getPage(), param.getLimit());
    }
    if(param.getSort() == null){
        param.setSort("id");
    }
    if(param.getOrder() == null){
        param.setOrder("");
    }
    GoodsExample goodsExample = new GoodsExample();
    //构造条件 → List<Criterion> → and方法做的事情就是构造一个Criterion的对象添加到List里
    // 如果 name 不为null，拼接条件 and name like '%songge%'
    GoodsExample.Criteria criteria = goodsExample.createCriteria();

    if (name != null && !"".equals(name)) {
        criteria.andNameLike("%" + name + "%");
    }
    if (goodsId != null && !"".equals(goodsId)) {
        criteria.andIdLike("%" + goodsId + "%");
    }
    if (goodsSn != null && !"".equals(goodsSn)) {
        criteria.andGoodsSnLike("%" + goodsSn + "%");
    }
    goodsExample.setOrderByClause(param.getSort() + " " + param.getOrder());
    List<Goods> goods = goodsMapper.selectByExample(goodsExample);
    return BasePageData.ok(goods);
}



    @Override
    public CatAndBrandVo catAndBrand() {
//        Brand brand = new Brand();

        BrandExample brandExample = new BrandExample();
        CategoryExample categoryExample = new CategoryExample();

        // 未删除
        categoryExample.createCriteria().andDeletedEqualTo(false);

        List<Brand> brands = brandMapper.selectByExample(brandExample);
        List<Category> categories = categoryMapper.selectByExample(categoryExample);
        CatAndBrandVo catAndBrandVo = new CatAndBrandVo(brands, categories);

//        return CatAndBrandVo.ok(brands,categories);
        return catAndBrandVo;
    }

    @Override
    public DetailVo detail(Integer id) {

        GoodsAttributeExample goodsAttributeExample = new GoodsAttributeExample();
        CategoryExample categoryExample = new CategoryExample();
        GoodsExample goodsExample = new GoodsExample();
        GoodsProductExample goodsProductExample = new GoodsProductExample();
        GoodsSpecificationExample goodsSpecificationExample = new GoodsSpecificationExample();


        GoodsExample.Criteria criteria = goodsExample.createCriteria();
        // 未删除
        criteria.andDeletedEqualTo(false);
        if (id != null && !id.equals("")){
            criteria.andIdEqualTo(id);
        }

        GoodsAttributeExample.Criteria goodsAttributeExampleCriteria = goodsAttributeExample.createCriteria();
        goodsAttributeExampleCriteria.andGoodsIdEqualTo(id);
        goodsAttributeExampleCriteria.andDeletedEqualTo(false);
        List<GoodsAttribute> goodsAttributes = goodsAttributeMapper.selectByExample(goodsAttributeExample);
        List<Integer> categoryIds =  categoryMapper.selectByExample2(categoryExample);
        Goods goods = goodsMapper.selectByPrimaryKey(id);

        GoodsProductExample.Criteria goodsProductExampleCriteria = goodsProductExample.createCriteria();
        goodsProductExampleCriteria.andGoodsIdEqualTo(id);
        goodsProductExampleCriteria.andDeletedEqualTo(false);
        List<GoodsProduct> goodsProducts = goodsProductMapper.selectByExample(goodsProductExample);

        GoodsSpecificationExample.Criteria goodsSpecificationExampleCriteria = goodsSpecificationExample.createCriteria();
        goodsSpecificationExampleCriteria.andGoodsIdEqualTo(id);
        goodsSpecificationExampleCriteria.andDeletedEqualTo(false);
        List<GoodsSpecification> goodsSpecifications = goodsSpecificationMapper.selectByExample(goodsSpecificationExample);
        DetailVo detailVo = new DetailVo(goodsAttributes, categoryIds, goods, goodsProducts, goodsSpecifications);
        return detailVo;
    }

    //商品信息修改
    @Override
    public void update(GoodsInfoVo goodsInfoVo) {

        //修改商品
        goodsMapper.updateByPrimaryKeySelective(goodsInfoVo.getGoods());

        //修改商品规格
        List<GoodsSpecification> specifications = goodsInfoVo.getSpecifications();
        for (GoodsSpecification specification : specifications) {
            goodsMapper.updateSpecification(specification);
        }

        //修改商品参数，id为不为空修改，为空就添加
        List<GoodsAttribute> attributes = goodsInfoVo.getAttributes();
        for (GoodsAttribute attribute : attributes) {
            if (attribute.getId() != null){
                goodsMapper.updateAttribute(attribute);
            }else {
                GoodsAttribute attribute1 = new GoodsAttribute(null,goodsInfoVo.getGoods().getId(), attribute.getAttribute(), attribute.getValue(),new Date(),new Date(),false);
                goodsMapper.addSingle(attribute1);
            }
        }

        //修改商品货品
        List<Product> products = goodsInfoVo.getProducts();
        for (Product product : products) {
            goodsMapper.updateProduct(product);
        }
    }

    @Override
    public void create(GoodsInfoBo goodsInfoBo) {
        GoodsExample goodsExample = new GoodsExample();
        GoodsExample.Criteria goodsCriteria = goodsExample.createCriteria();

        // 先处理商品，其它都需要商品id连接信息
        Goods goodsBo = goodsInfoBo.getGoods();
        Date date = new Date();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");

        // 零售价格
        BigDecimal retailPrice;
        if(goodsBo.getCounterPrice().compareTo(BigDecimal.valueOf(1000)) < 1 ){
            // 专柜价小于1000
            retailPrice = goodsBo.getCounterPrice().add(BigDecimal.valueOf((long)new Random().nextInt(100)));
        } else if(goodsBo.getCounterPrice().compareTo(BigDecimal.valueOf(10000)) < 1){
            retailPrice = goodsBo.getCounterPrice().add(BigDecimal.valueOf((long)new Random().nextInt(1000)));
        } else {
            retailPrice = goodsBo.getCounterPrice().add(BigDecimal.valueOf((long)new Random().nextInt(10000)));
        }

        Goods goods = new Goods(null,goodsBo.getGoodsSn(),goodsBo.getName(),goodsBo.getCategoryId(),
                goodsBo.getBrandId(),goodsBo.getGallery(),goodsBo.getKeywords(),goodsBo.getBrief(),goodsBo.getIsOnSale(),
                Short.parseShort("1"),goodsBo.getPicUrl(),null,goodsBo.getIsNew(),goodsBo.getIsHot(),
                goodsBo.getUnit(),goodsBo.getCounterPrice(),retailPrice,date,date,false,goodsBo.getDetail());
        goodsMapper.insertSelective(goods);

        //根据商品编号获取商品id
        if(goods.getGoodsSn() != null && !goods.getGoodsSn().equals("")){
            goodsCriteria.andGoodsSnEqualTo(goods.getGoodsSn());
        }
        // 双重保障，嘿嘿
        if(goods.getName() != null && !goods.getName().equals("")){
            goodsCriteria.andNameEqualTo(goods.getName());
        }
        List<Goods> goodsList = goodsMapper.selectByExample(goodsExample);
        Goods goodsRead = goodsList.get(0); // 唯一
        // 商品id
        Integer goodsId = goodsRead.getId();

        // 商品规格specification
        List<GoodsSpecification> specifications = goodsInfoBo.getSpecifications();
        for (GoodsSpecification specification : specifications) {
            specification = new GoodsSpecification(null,goodsId,
                    specification.getSpecification(),specification.getValue(),specification.getPicUrl(),
                    date,date,false);
            goodsSpecificationMapper.insertSelective(specification);
        }

        // 商品参数 attribute
        List<GoodsAttribute> attributes = goodsInfoBo.getAttributes();
        for (GoodsAttribute attribute : attributes) {
            attribute = new GoodsAttribute(null,goodsId,attribute.getAttribute(),
                    attribute.getValue(),date,date,false);
            goodsAttributeMapper.insertSelective(attribute);
        }

        // 商品产品
        List<GoodsProduct> products = goodsInfoBo.getProducts();
        for (GoodsProduct product : products) {
            product = new GoodsProduct(null,goodsId,product.getSpecifications(),product.getPrice(),
                    product.getNumber(),product.getUrl(),date,date,false);
            goodsProductMapper.insertSelective(product);
        }

    }

    @Override
    public void delete(Goods goods) {
        GoodsProductExample goodsProductExample = new GoodsProductExample();
        GoodsProductExample.Criteria goodsProductExampleCriteria = goodsProductExample.createCriteria();
        GoodsSpecificationExample specificationExample = new GoodsSpecificationExample();
        GoodsSpecificationExample.Criteria specificationExampleCriteria = specificationExample.createCriteria();
        GoodsAttributeExample attributeExample = new GoodsAttributeExample();
        GoodsAttributeExample.Criteria attributeExampleCriteria = attributeExample.createCriteria();

        // 删除商品信息
        goodsMapper.deleteByPrimaryKey(goods.getId());
        if(goods.getId() != null){
            goodsProductExampleCriteria.andGoodsIdEqualTo(goods.getId());
        }
        // 删除产品信息
        goodsProductMapper.deleteByExample(goodsProductExample);
        // 删除规格信息
        if(goods.getId() != null){
            specificationExampleCriteria.andGoodsIdEqualTo(goods.getId());
        }
        goodsSpecificationMapper.deleteByExample(specificationExample);
        // 删除参数信息
        if(goods.getId() != null){
            attributeExampleCriteria.andGoodsIdEqualTo(goods.getId());
        }
        goodsAttributeMapper.deleteByExample(attributeExample);
    }

    @Override
    public CateAndBrandVo getCateAndBrand() {
        CategoryExample categoryExample = new CategoryExample();
        CategoryExample.Criteria categoryCriteria = categoryExample.createCriteria();
        BrandExample brandExample = new BrandExample();
        BrandExample.Criteria brandCriteria = brandExample.createCriteria();

        // 查询品牌没有条件，查询所有
        List<Brand> brandList = brandMapper.selectByExample(brandExample);
        List<GoodsBrandVo> goodsBrandVos = new ArrayList<>();
        for (Brand brand : brandList) {
            GoodsBrandVo goodsBrandVo = new GoodsBrandVo(brand.getId(), brand.getName());
            goodsBrandVos.add(goodsBrandVo);
        }
        // 设置连接条件,查询所有的一级类目
        categoryCriteria.andPidEqualTo(0);

        List<Category> categoryList = categoryMapper.selectByExample(categoryExample);
        List<Category> categoryChildrenList = null;
        List<GoodsCategoryVo> goodsCategoryVos = new ArrayList<>();
        for (Category category : categoryList) {
            CategoryExample categoryChildExample = new CategoryExample();
            CategoryExample.Criteria categoryChildCriteria = categoryChildExample.createCriteria();
            // 二级类目
            categoryChildCriteria.andPidEqualTo(category.getId());
            categoryChildrenList = categoryMapper.selectByExample(categoryChildExample);
            // 给一级类目赋值
            GoodsCategoryVo goodsCategoryVo = new GoodsCategoryVo();
            goodsCategoryVo.setValue(category.getId());
            goodsCategoryVo.setLabel(category.getName());
            List<CategoryIdAndNameVo> categoryIdAndNameVos = new ArrayList<>();
            for (Category categoryChild : categoryChildrenList) {
                // 给二级类目赋值
                categoryIdAndNameVos.add(new CategoryIdAndNameVo(categoryChild.getId(),categoryChild.getName()));
            }
            goodsCategoryVo.setChildren(categoryIdAndNameVos);
            goodsCategoryVos.add(goodsCategoryVo);
        }

        CateAndBrandVo cateAndBrandVo = new CateAndBrandVo();
        cateAndBrandVo.setCategoryList(goodsCategoryVos);
        cateAndBrandVo.setBrandList(goodsBrandVos);
        return cateAndBrandVo;
    }

    /**
     *  小程序 根据商品id获取商品详情
     *
     * @param goodsId
     * @return
     */
    @Override
    public WxGoodsDetailVo getWxDetail(Integer goodsId,Integer userId) {
        GoodsExample goodsExample = new GoodsExample();
        GoodsExample.Criteria goodsCriteria = goodsExample.createCriteria();
        GoodsSpecificationExample goodsSpecificationExample = new GoodsSpecificationExample();
        GoodsSpecificationExample.Criteria specificationCriteria = goodsSpecificationExample.createCriteria();
        GoodsAttributeExample attributeExample = new GoodsAttributeExample();
        GoodsAttributeExample.Criteria attributeCriteria = attributeExample.createCriteria();
        GoodsProductExample goodsProductExample = new GoodsProductExample();
        GoodsProductExample.Criteria productCriteria = goodsProductExample.createCriteria();
        IssueExample issueExample = new IssueExample();
        CommentExample commentExample = new CommentExample();
        CommentExample.Criteria commentExampleCriteria = commentExample.createCriteria();
        UserExample userExample = new UserExample();
        UserExample.Criteria userCriteria = userExample.createCriteria();
        BrandExample brandExample = new BrandExample();
        BrandExample.Criteria brandCriteria = brandExample.createCriteria();

        // 获取用户的头像
        if(userId != null){
            userCriteria.andIdEqualTo(userId);
        }
        List<User> userList = userMapper.selectByExample(userExample);
        String avatar = userList.get(0).getAvatar();

        // 查询规格信息
        if(goodsId != null){
            specificationCriteria.andGoodsIdEqualTo(goodsId);
        }
        List<GoodsSpecification> specificationList = goodsSpecificationMapper.selectByExample(goodsSpecificationExample);
        // 要添加的规格列表
        List<SpecificationListDTO> specificationListDTOS = new ArrayList<>();
        // 遍历获取商品规格的名称和信息
        for (GoodsSpecification goodsSpecification : specificationList) {
            List<GoodsSpecification> valueList = new ArrayList<>();
            valueList.add(goodsSpecification);
            SpecificationListDTO specificationListDTO =
                    new SpecificationListDTO(goodsSpecification.getSpecification(),valueList);
            specificationListDTOS.add(specificationListDTO);
        }

        // 团购活动列表
        List<GroupOn> groupOn = new ArrayList<>();

        //  帮助列表
        List<Issue> issueList = issueMapper.selectByExample(issueExample);

        // userHasCollect
        Goods goods = goodsMapper.selectByPrimaryKey(goodsId);
        Integer userHasCollect = goods.getGallery().length;

        // 品牌id，后面会用
        Integer brandId = goods.getBrandId();

        // shareImage
        String shareImgeUrl = goods.getShareUrl();

        // 评价列表
        if(userId != null){
            commentExampleCriteria.andUserIdEqualTo(userId);
            // 获取商品评论 valueId是0
//            commentExampleCriteria.andValueIdEqualTo(0);      // 修改：value_id 是商品id，等于0，没有评论
            commentExampleCriteria.andValueIdEqualTo(goodsId);  // 修改：value_id 是商品id，查询的是同一个商品的评论
        }
        List<Comment> commentList = commentMapper.selectByExample(commentExample);
        List<CommentInnerVo> data = new ArrayList<>();
        // 评价是否包含图片
        Boolean share = false;
        for (Comment comment : commentList) {
            CommentInnerVo commentInnerVo = new CommentInnerVo(comment.getAddTime(),
                    avatar,comment.getContent(),comment.getId(),userList.get(0).getNickname(),
                    comment.getPicUrls());
            data.add(commentInnerVo);
            // 有图片评价，就将share赋值为true
            if(comment.getHasPicture()){
                share = true;
            }
        }
        CommentDTO commentDTO = new CommentDTO(data,commentList.size());

        // 商品参数列表
        if(goodsId != null){
            attributeCriteria.andGoodsIdEqualTo(goodsId);
        }
        List<GoodsAttribute> attributes = goodsAttributeMapper.selectByExample(attributeExample);

        // 商品品牌
        if(goodsId != null){
            brandCriteria.andIdEqualTo(brandId);
        }
        Brand brand = brandMapper.selectByPrimaryKey(brandId);

        // 商品产品列表
        if(goodsId != null){
            productCriteria.andGoodsIdEqualTo(goodsId);
        }
        List<GoodsProduct> productList = goodsProductMapper.selectByExample(goodsProductExample);

        // 商品信息，上面已查出来了

        // 赋值，返回
        WxGoodsDetailVo wxGoodsDetailVo = new WxGoodsDetailVo(specificationListDTOS, groupOn, issueList, userHasCollect, shareImgeUrl,
                commentDTO, share, attributes, brand, productList, goods);
        return wxGoodsDetailVo;
    }

    @Override
    public List<Goods> getRelated(Integer goodsId) {
        GoodsExample goodsExample = new GoodsExample();
        GoodsExample.Criteria goodsExampleCriteria = goodsExample.createCriteria();
        // 获取当前商品的对象
        Goods goods = goodsMapper.selectByPrimaryKey(goodsId);
        // 获取相同类目下的商品
        goodsExampleCriteria.andCategoryIdEqualTo(goods.getCategoryId());
        List<Goods> goodsList = goodsMapper.selectByExample(goodsExample);
        return goodsList;
    }

    @Override
    public int getAllGoodsNum() {
        GoodsExample goodsExample = new GoodsExample();
        List<Goods> goodsList = goodsMapper.selectByExample(goodsExample);
        return goodsList.size();
    }

    /**
     *  新品销售
     *  根据is_new 字段是1，获取指定的商品列表
     *
     * @return
     */
    @Override
    public List<Goods> getNewGoodsList() {
        GoodsExample goodsExample = new GoodsExample();
        GoodsExample.Criteria goodsExampleCriteria = goodsExample.createCriteria();
        // 获取is_new是1的商品
        goodsExampleCriteria.andIsNewEqualTo(true);
        List<Goods> goodsList = goodsMapper.selectByExample(goodsExample);
        return LimitListSizeUtil.limitSize(goodsList);
    }

    /**
     *  获取所有热卖的商品
     *
     * @return
     */
    @Override
    public List<Goods> getHotGoodsList() {
        GoodsExample goodsExample = new GoodsExample();
        GoodsExample.Criteria goodsExampleCriteria = goodsExample.createCriteria();
        goodsExampleCriteria.andIsHotEqualTo(true);
        List<Goods> goodsList = goodsMapper.selectByExample(goodsExample);
        return LimitListSizeUtil.limitSize(goodsList);
    }

    /**
     *  获取一级类目下的推荐商品
     *
     * @return
     */
    @Override
    public List<WxHomeIndexFloorGoodsVo> getWxHomeIndexFloorGoods(List<Category> categoryList) {
        List<WxHomeIndexFloorGoodsVo> wxHomeIndexFloorGoodsVoList = new ArrayList<>();
        // 遍历一级类目
        for (Category category : categoryList) {
            GoodsExample goodsExample = new GoodsExample();
            GoodsExample.Criteria goodsExampleCriteria = goodsExample.createCriteria();
            CategoryExample categoryExample = new CategoryExample();
            CategoryExample.Criteria categoryExampleCriteria = categoryExample.createCriteria();
            categoryExampleCriteria.andPidEqualTo(category.getId());
            List<Category> categories = categoryMapper.selectByExample(categoryExample);

            for (Category categorySecond : categories) {
                goodsExampleCriteria.andCategoryIdEqualTo(categorySecond.getId());
                List<Goods> goodsList = goodsMapper.selectByExample(goodsExample);
                WxHomeIndexFloorGoodsVo wxHomeIndexFloorGoodsVo
                        = new WxHomeIndexFloorGoodsVo(category.getId(),category.getName(),LimitListSizeUtil.limitSize(goodsList));
                wxHomeIndexFloorGoodsVoList.add(wxHomeIndexFloorGoodsVo);
            }
        }
        return wxHomeIndexFloorGoodsVoList;
    }

    @Override
    public Goods selectDefaultKeyword(Integer goodsId) {
        Goods goods = goodsMapper.selectByPrimaryKey(goodsId);
        return goods;
    }

    /**
     *  获取热门关键字列表
     *
     * @param defaultKeyword
     * @return
     */
    @Override
    public List<Goods> getHotKeywordList(Goods defaultKeyword) {
        List<Goods> hotKeywordList = new ArrayList<>();
        hotKeywordList.add(defaultKeyword);
        // 搜索热门和新品的商品列表
        List<Goods> hotAndNewGoodsList = goodsMapper.selectHotAndNewGoods();
        hotKeywordList.addAll(hotAndNewGoodsList);
        return LimitListSizeUtil.limitSize(hotKeywordList);
    }
}
